<?php declare(strict_types=1);
/**
 * Created by IntelliJ IDEA
 * Author: 张伯发
 * Date  : 2019/11/18
 * Time  : 23:13
 */

namespace Xiaoproject\Common\Json;

use Xiaoproject\Common\Constant\Response;

class JsonBuilder
{
    /**
     * 格式化数据
     * @param int $code 状态码 0 成功
     * @param mixed $data 数据体
     * @param string $msg 信息
     * @return array
     */
    public function P(int $code = Response::CODE_SUCCESS, $data = null, string $msg = '')
    {
        $parseData = array();
        if (empty($msg)) $msg = Response::TEXT_SUCCESS;

        try {
            if (is_object($data)) $data = obj2Array($data);
        } catch (\ReflectionException $e) {
            $data = [];
        }
        $parseData['code'] = $code;
        $parseData['data'] = $data;
        $parseData['msg'] = $msg;
        return $parseData;
    }

    /**
     * 正确返回
     * @param string $msg
     * @param mixed $data
     * @return array
     */
    public function SMessage(string $msg = '', $data = null)
    {
        return $this->P(Response::CODE_SUCCESS, $data,$msg);
    }

    /**
     *
     * @param mixed $data
     * @param string $msg
     * @return array
     * @author 张伯发 2019/11/18 23:21
     */
    public function S($data = null, string $msg = '')
    {
        return $this->P(Response::CODE_SUCCESS, $data, $msg);
    }

    /**
     * 错误返回
     * @param $msg
     * @return array
     */
    public function E(string $msg)
    {
        return $this->P(Response::CODE_ERROR, null, $msg);
    }
}
